import React, { useState, useEffect, Fragment } from 'react';
import { Form, Row, Col, Button, Icon, Divider } from 'antd';
import { withRouter, router } from 'umi';
import useMediaQuery from 'use-media-antd-query';
import PropTypes from 'prop-types';
import cn from 'classnames';
import styles from './AdvancedSearch.less';

/**
 * 默认的搜索表单配置
 */
const defaultColConfig = {
    xxl: 6,
    xl: 8,
    lg: 12,
    md: 24,
    sm: 24,
    xs: 24
};

/**
 * 获取当前span的大小
 */
const getSpanConfig = (span, size) => {
    if (typeof span === 'number') {
        return span;
    }
    const config = {
        ...defaultColConfig,
        ...span
    };
    return config[size];
};

const AdvancedSearch = props => {
    const { form, onReset, onSubmit, extraButtons, formStyle, colConfig, children, location } = props;
    const { query } = location;
    const { isExpand } = query;
    const windowSize = useMediaQuery();
    const [colSize, setColSize] = useState(getSpanConfig(defaultColConfig, windowSize));
    const rowNumber = 24 / colSize || 3;
    const finalColConfig = colConfig ? { ...defaultColConfig, ...colConfig } : { ...defaultColConfig };
    useEffect(() => {
        setColSize(getSpanConfig(colConfig, windowSize));
    }, [windowSize]);

    const [expand, setExpand] = useState(
        typeof isExpand === 'undefined' ? !!props.expand : isExpand === '1' || isExpand === 1 || false
    );
    const childrenArr = React.Children.map(children, (item, index) => ({ ...item, key: index })).filter(item =>
        React.isValidElement(item)
    );
    const count = childrenArr.length;

    // 获取表单项数组
    const getFields = () => {
        let cnt = count;
        if (cnt > rowNumber - 1) {
            cnt = expand ? count : rowNumber - 1;
            if (cnt === 0) {
                cnt = 1;
            }
        }
        const arr = childrenArr.map((item, index) => {
            if (index < cnt) {
                return (
                    <Col {...finalColConfig} key={item.key}>
                        {item}
                    </Col>
                );
            }
            return (
                <Col {...finalColConfig} key={item.key} style={{ display: 'none' }}>
                    {item}
                </Col>
            );
        });
        return arr;
    };

    const handleSubmit = e => {
        e.preventDefault();
        onSubmit();
    };

    const handleReset = () => {
        form.resetFields();
        if (onReset) onReset();
    };

    const handleExpand = () => {
        setExpand(!expand);
        history.push({
            query: {
                ...query,
                isExpand: expand ? 0 : 1
            }
        });
    };

    // 获取按钮
    const getBtn = () => {
        if (count >= 2 && count > rowNumber - 1) {
            return (
                <Col {...finalColConfig} style={{ textAlign: 'right', paddingTop: 4, paddingBottom: 4 }} key="btn">
                    {count > rowNumber - 1 && (
                        <Button type="link" style={{ padding: '0 12px' }} onClick={handleExpand}>
                            {expand ? '收起' : '更多'} <Icon type={expand ? 'up' : 'down'} />
                        </Button>
                    )}
                    <Button type="link" style={{ padding: '0 12px' }} onClick={handleReset}>
                        清空
                    </Button>
                    <Button type="primary" htmlType="submit" style={{ marginLeft: 12 }}>
                        搜索
                    </Button>
                </Col>
            );
        }
        return (
            <Button type="primary" htmlType="submit" key="btn" style={{ marginLeft: 16 }}>
                搜索
            </Button>
        );
    };

    // 获取最终渲染的数组
    const getChildren = () => {
        const arr = getFields();
        if (expand && count >= 2 && count > rowNumber - 1) {
            if ((count + 1) % rowNumber !== 0) {
                const c = Math.ceil((count + 1) / rowNumber);
                const len = c * rowNumber - count - 1;
                new Array(len).fill(1).forEach((item, i) => {
                    arr.push(
                        <Col {...finalColConfig} key={`empty${i + item}`}>
                            <div></div>
                        </Col>
                    );
                });
            }
        }
        arr.push(getBtn());
        return arr;
    };

    return (
        <Fragment>
            <Form
                layout="inline"
                name="advancedSearch"
                className={cn({ [styles.advancedSearch]: true, [styles.countOne]: count === 1 })}
                onSubmit={handleSubmit}
                style={{ ...formStyle }}
            >
                <Row type="flex" span={24} gutter={16} style={{ alignItems: 'center' }}>
                    {getChildren()}
                </Row>
            </Form>
            {extraButtons && <Divider dashed style={{ margin: '16px 0 16px' }} />}
            {extraButtons && (
                <Row
                    type="flex"
                    span={24}
                    style={{
                        justifyContent: 'flex-end',
                        alignItems: 'center',
                        paddingBottom: 16
                    }}
                >
                    {extraButtons}
                </Row>
            )}
        </Fragment>
    );
};

AdvancedSearch.propTypes = {
    form: PropTypes.any, // form
    onReset: PropTypes.func, // 重置操作
    onSubmit: PropTypes.func, // 提交操作
    extraButtons: PropTypes.element, // 下方按钮
    expand: PropTypes.bool, // 默认是否展开(非必填)
    formStyle: PropTypes.object, // 表单额外样式
    colConfig: PropTypes.object // 自适应比例配置
};

AdvancedSearch.defaultProps = {
    form: null,
    onReset: () => {},
    onSubmit: () => {},
    extraButtons: null,
    expand: false,
    formStyle: {},
    colConfig: null
};

export default withRouter(AdvancedSearch);
